//
//  UserDetailSetting.swift
//  YoruNeko
//
//  Created by Kotori on 2021/6/21.
//

import SwiftUI

struct UserDetailSetting: View {
    //FakeData
    var uuidString: String = UserPreferenceManager.anonymous
    @State var myUserMgr: UserPreferenceManager = UserPreferenceManager.manager(of: nil)
    @State var isSync: Bool = false
    @State var logoutAlert: Bool = false
    var body: some View {
        VStack {
            List {
                UserDetailView(userMgr: myUserMgr)
                Button {
                    //显示注销告警提示框
                    logoutAlert.toggle()
                } label: {
                    Text("注销账户")
                }
                .foregroundColor(.red)
                .disabled(myUserMgr.getUsername() == "anonymous")
                .alert(isPresented: $logoutAlert){
                    Alert(title: Text("确认注销账号"), message: Text("将改为使用默认账号登录"), primaryButton: .cancel(), secondaryButton: .default(Text("确认"), action: {
                        //注销账户流程
                        print("注销账户流程")
                        UserManager.setCurrUser(uuidString: UserPreferenceManager.anonymous)
                    }))
                }
                
                Section(header: Text("同步设置")) {
                    Toggle("开启同步", isOn: $isSync)
                        .onChange(of: isSync, perform: { isSync in
                            print("切换同步状态至\(isSync)")
                            myUserMgr.setSync(sync: isSync)
                        })

                    if (isSync) {
                        //展示可同步选项
                        withAnimation(.easeIn) {
                            Text("最近同步：无").font(.subheadline).foregroundColor(.gray)
                        }
                    }
                }
            }
        }
        .onAppear(perform: {
            myUserMgr = UserPreferenceManager.manager(of: UUID(uuidString: uuidString))
            isSync = myUserMgr.getSync()
        })
        .onDisappear(perform: {
            //退出页面流程，持久化设置
            print("持久化设置")
            myUserMgr.commit()
        })
    }
}

struct UserDetailView: View {
    //FakeData
    var userMgr: UserPreferenceManager
    
    var avatar: Image = Image(systemName: "person.badge.plus")
    var body: some View {
        HStack {
            avatar
                .frame(width: 50, height: 50, alignment: .center)
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.black, lineWidth: 1))
            
            VStack(alignment: .leading) {
                Text(userMgr.getUsername())
            }
            .padding(.horizontal)
            Spacer()
        }
        .frame(height: 60)
    }
}

struct UserDetailSetting_Previews: PreviewProvider {
    static var previews: some View {
        UserDetailSetting()
    }
}
